package com.goods.business.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goods.business.mapper.ProductStockMapper;
import com.goods.business.service.ProductStockService;
import com.goods.common.model.business.InStockInfo;
import com.goods.common.model.business.OutStockInfo;
import com.goods.common.model.business.ProductStock;
import com.goods.common.vo.business.ProductStockVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：Hachimen
 * @date ：Created in 2021/9/27 9:00
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class ProductStockServiceImpl implements ProductStockService {
    @Autowired
    private ProductStockMapper productStockMapper;

    @Override
    public PageInfo<ProductStockVO> findProductStocks(String pageNum, String pageSize, String categorys, String name) {
        if(!StringUtils.isEmpty(pageNum)&&!StringUtils.isEmpty(pageSize)){
            PageHelper.startPage(Integer.parseInt(pageNum),Integer.parseInt(pageSize));
        }
        if(!StringUtils.isEmpty(categorys)){
            String[] split = categorys.split(",");
            if(split.length == 3){
                categorys = split[2];
            }else{
                categorys = "";
            }

        }

        Map<String, String> map = new HashMap<>();
        map.put("categorys",categorys);
        map.put("name",name);
        List<ProductStockVO> list = productStockMapper.findProductStocks(map);
        /*for (ProductStockVO productStockVO : list) {
            if(productStockVO.getStock()==null){
                productStockVO.setStock(0L);
            }
        }
*/

        return new PageInfo<ProductStockVO>(list);
    }

    @Override
    public void add(InStockInfo inStockInfo) {
        //加库存
        Example example = new Example(ProductStock.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("pNum",inStockInfo.getpNum());
        ProductStock productStocks = productStockMapper.selectOneByExample(example);
        productStocks.setStock(productStocks.getStock()+inStockInfo.getProductNumber());
        productStockMapper.updateByPrimaryKey(productStocks);
    }

    @Override
    public void sub(OutStockInfo outStockInfo) {
        //减库存
        Example example = new Example(ProductStock.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("pNum",outStockInfo.getpNum());
        ProductStock productStocks = productStockMapper.selectOneByExample(example);
        productStocks.setStock(productStocks.getStock()-outStockInfo.getProductNumber());
        productStockMapper.updateByPrimaryKey(productStocks);
    }
}
